package com.yupi.yuapigateway;
import com.yupi.yuapiclientsdk.utils.SignUtils;
import com.yupi.yuapicommon.model.entity.InterfaceInfo;
import com.yupi.yuapicommon.model.entity.User;
import com.yupi.yuapicommon.service.InnerInterfaceInfoService;
import com.yupi.yuapicommon.service.InnerUserInterfaceInfoService;
import com.yupi.yuapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 */


//  1、用户发送请求到API网关
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
    private static final String INTERFACE_HOST = "http://localhost:8123";

//使用Dubbo框架RPC调用后端方法--此注解类比bean引入的@Resource
    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    @DubboReference
    private InnerUserService innerUserService;
    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //  2、请求日志
        //根据exchange 拦截获取到前端发出的请求
        ServerHttpRequest request = exchange.getRequest();
        //获取前端请求的映射路径，并拼接成模拟接口的 完整请求地址
        String path = INTERFACE_HOST + request.getPath().value();
        //拦截获取请求的方法
        String method = request.getMethod().toString();
        log.info("请求唯一标识：" + request.getId());
        log.info("请求路径：" + path);
        log.info("请求方法：" + method);
        log.info("请求参数：" + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址：" + sourceAddress);
        log.info("请求来源地址：" + request.getRemoteAddress());
        ServerHttpResponse response = exchange.getResponse();


    //  3、访问控制 --- （黑白名单）
        //通过exchange获取请求信息，再控制响应
        if(!IP_WHITE_LIST.contains(sourceAddress)){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            log.info("不允许访问");
            return response.setComplete();
        }

/**
accessKey是身份标识，根据请求者accessKey在数据库中拿到对用的有资格用户User，并拿到对应的secretKey，和请求者的body现场生成serverSign
 请求者在发送请求时就会调用签名生成工具生成签名sign，存储在请求头中，拿出来。
  将sign与serverSign对比。
 ak-sk机制：
 请求者根据ak-sk已经生成了签名，在发送请求时，将ak和sign一起放在请求头中，
 API网关拿到请求头中的ak与sign，根据ak去数据库确定是哪个用户，拿到对应的sk，重新生成serverSign，再完成签名校验。

 */
    //  4、用户鉴权（判断ak、sk是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        // todo 实际情况是应该去数据库中查是否已分配给用户
        User invokeUser = null;
        try{
            invokeUser = innerUserService.getInvokeUser(accessKey);
        }catch(Exception e){
            log.error("getInvokeUser error",e);
        }
        if(invokeUser == null){
            return handleNoAuth(response);
        }

        if(Long.parseLong(nonce) > 10000L ){
            return handleNoAuth(response);
        }
        //  时间和当前时间不能超过5min
        Long currentTime = System.currentTimeMillis() / 1000;
        final Long FIVE_MINUTES = 60 * 5L;
        if((currentTime - Long.parseLong(timestamp)) >= FIVE_MINUTES){
            return handleNoAuth(response);
        }
/**
 * 签名认证：
 * 根据发送请求对象User取出来的secretKey使用body进行加密（实际的），再和客户端加密得到的秘钥比对
 * 也就是要对比
 */
        //     实际情况是从数据库中查出secretKey
        String secretKey = invokeUser.getSecretKey();
//        服务器根据请求对象的secretKey和body现场生成签名

        String serverSign = SignUtils.genSign(body,secretKey);
        log.info("1:" + secretKey);
        log.info("2:" + serverSign);
        log.info("3:" + sign);
        if(sign == null || !sign.equals(serverSign)){
            return handleNoAuth(response);
        }
         // todo 校验是否还有调用次数




    //  5、请求的模拟接口是否存在，以及请求方法是否匹配
        /** 根据请求方法&请求路径在数据库中查找对应的 接口
            所以一定要注意请求方法还有请求地址 要和数据库中的url和method对应好
         */
        InterfaceInfo  interfaceInfo = null;
        try{
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
            log.info("请求路径===" + path);
            log.info("请求方法===" + method);
            log.info("原始调用====" + String.valueOf(innerInterfaceInfoService.getInterfaceInfo(path, method)));
            log.info("接口信息===" + String.valueOf(interfaceInfo));
        }catch(Exception e){
            log.error("getInterfaceInfo error",e);
        }
        if(interfaceInfo == null){
            return handleNoAuth(response);
        }


        // todo 从数据库中查询模拟接口是否存在， （还可以校验请求参数）
     //  6、请求转发，调用模拟接口
        //        Mono<Void> filter = chain.filter(exchange);
        //         return filter;


         return handleResponse(exchange,chain,interfaceInfo.getId(),invokeUser.getId());


    }


    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long interfaceInfoId,long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. todo 调用成功，接口调用次数 + 1 invokeCount
                                        try {
//                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }
    public Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }
    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}



